﻿using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq; 


class YoudaoApiExample
{
    private static readonly string appKey = "1112e236a2d45bf8"; // 有道应用ID
    private static readonly string appSecret = "BlgxjT3OIrn1aTplvzbz6bTfDF6M0Ky2"; // 有道应用密钥
    private static readonly string apiUrl = "https://openapi.youdao.com/api"; // 有道API的URL

    static async Task Main(string[] args)
    {
        string textToTranslate = "To go into solitude, a man needs to retire as much from his chamber as from society.";
        string translatedText = await Translate(textToTranslate, "en", "zh-CHS");
        Console.WriteLine(translatedText);
    }
    public static async Task<string> Translate(string q, string from, string to)
    {
        string salt = Guid.NewGuid().ToString(); // 生成随机的UUID作为salt
        string curtime = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds).ToString(); // 当前UTC时间的时间戳
        string input = GetInputString(q); // 计算input
        string signStr = appKey + input + salt + curtime + appSecret; // 拼接字符串，用于生成签名
        string sign = ComputeSha256Hash(signStr); // 生成SHA-256签名

        // 构建请求参数
        var parameters = new StringBuilder();
        parameters.AppendFormat("q={0}", Uri.EscapeDataString(Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(q))));
        parameters.AppendFormat("&from={0}", Uri.EscapeDataString(from));
        parameters.AppendFormat("&to={0}", Uri.EscapeDataString(to));
        parameters.AppendFormat("&appKey={0}", appKey);
        parameters.AppendFormat("&salt={0}", salt);
        parameters.AppendFormat("&sign={0}", sign);
        parameters.AppendFormat("&signType=v3");
        parameters.AppendFormat("&curtime={0}", curtime);

        using (var client = new HttpClient())
        {
            // 发送HTTP GET请求
            var response = await client.GetStringAsync(apiUrl + "?" + parameters.ToString());
            return ParseTranslation(response); // 返回API返回的结果
        }
    }
    private static string ParseTranslation(string response)
    {
        JObject jsonResponse = JObject.Parse(response);
        if (jsonResponse["errorCode"].ToString() == "0")
        {
            JArray translationArray = (JArray)jsonResponse["translation"];
            return translationArray[0].ToString();
        }
        else
        {
            return "翻译失败，错误代码：" + jsonResponse["errorCode"];
        }
    }
    // 计算SHA-256哈希值
    private static string ComputeSha256Hash(string rawData)
    {
        using (SHA256 sha256Hash = SHA256.Create())
        {
            byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(rawData));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }

    // 计算input字符串
    private static string GetInputString(string q)
    {
        if (q.Length > 20)
        {
            return q.Substring(0, 10) + q.Length + q.Substring(q.Length - 10);
        }
        else
        {
            return q;
        }
    }
}
